//
//  YDVerticalStockNewDetailController.m
//  PeiZiWangBei
//
//  Created by LK-IOS on 2018/1/10.
//  Copyright © 2018年 LK-IOS. All rights reserved.
//

#import "YDVerticalStockNewDetailController.h"
#import <WebKit/WebKit.h>
#import "YDSingleStockNewsModel.h"
#import "YDVerticalStockNewDetailTitleView.h"


@interface YDVerticalStockNewDetailController ()<WKNavigationDelegate , WKUIDelegate>
@property (nonatomic , copy) NSString *contentString;
@property (nonatomic , weak) UIProgressView *progressView;
@property (nonatomic , weak) WKWebView *webView;
@property (nonatomic , weak) UIActivityIndicatorView *activityView;

@end

@implementation YDVerticalStockNewDetailController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"新闻";
    [self activityView];
    [self progressView];    
    [self loadNewData];
    
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    
}

-(UIActivityIndicatorView *)activityView
{
    if (_activityView == nil) {
        UIActivityIndicatorView *activityView = [UIActivityIndicatorView new];
        [self.view addSubview:activityView];
        activityView.hidesWhenStopped = YES;
        activityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
        [activityView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(20, 20));
        }];
        _activityView = activityView;
    }
    return _activityView;
}


/**
 加载新闻数据 ， 加载完数据之后交给web显示
 */
-(void)loadNewData
{
    
    DDLog(@"self.style = %zd" , self.style)
    
    if (!self.model.Id.length) {
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"暂无详情" isExistNav:YES];
        return;
    }
    [self.activityView startAnimating];
    RequestType type = self.style ? WeekNewsDetail : GetNewsDetail;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:self.model.Id forKey:@"id"];
    
    [BaseNetRequest sessionRequestWithparameters:dict method:GETMethod requstType:type WithSuccessBlock:^(NSDictionary *resultDict) {
        [self.activityView stopAnimating];
        if ([resultDict[@"code"] integerValue] == 200) {
            //获取详情字段
            self.contentString = [NSString stringWithFormat:@"%@" , resultDict[@"data"][@"content"]];
            [self addWebView];
        }else{
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"数据加载出错" isExistNav:YES];
            return ;
        }
    } failBlock:^(NSError *error) {
        [self.activityView stopAnimating];
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"数据加载出错" isExistNav:YES];
        return ;
    }];

}

-(void)addWebView
{
    
    NSMutableString *javascript = [NSMutableString string];
    
//    [javascript appendString:@"document.documentElement.style.webkitTouchCallout='none';"];//禁止长按
//    [javascript appendString:@"document.documentElement.style.webkitUserSelect='none';"];//禁止选择
    [javascript appendString:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no'); document.getElementsByTagName('head')[0].appendChild(meta);"];
    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    
    //配置对象
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    [wkUController addUserScript:wkUScript];
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    WKPreferences *preference = [[WKPreferences alloc]init];
    preference.minimumFontSize = 16;
    config.preferences = preference;
    config.userContentController = wkUController;
    
    
    WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    
    webView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleLeftMargin;
    webView.backgroundColor = [UIColor whiteColor];
    webView.navigationDelegate = self;
    webView.UIDelegate = self;
    webView.opaque = NO;
    webView.multipleTouchEnabled = YES;
    [self.view insertSubview:webView belowSubview:_progressView];

    [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
     self.webView = webView;
    
    
    NSString *content = [self.contentString stringByReplacingOccurrencesOfString:@"&amp;quot" withString:@"'"];
    //替换部分特殊字符
    content = [content stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    content = [content stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    content = [content stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
    
    //设置显示格式 ， 图片 ， 字体等
    NSString *htmls;
    if (self.style) {
        htmls = [NSString stringWithFormat:@"<html> \n"
                           "<head> \n"
                           "<style type=\"text/css\"> \n"
                           "body {font-size:.5rem;color:#1e242e;text-indent:1.26rem;padding:0 .26rem;letter-spacing: .02rem;text-align: justify;}\n"
                           "</style> \n"
                           "</head> \n"
                           "<body>"
                           "<script type='text/javascript'>"
                           "window.onload = function(){\n"
                           "var $img = document.getElementsByTagName('img');\n"
                           "for(var p in  $img){\n"
                           " $img[p].style.width = '100%%';\n"
                           "$img[p].style.height ='auto'\n"
                           "}\n"
                           "}"
                           "</script>%@"
                           "</body>"
                           "</html>",content];
    }else{
        htmls = [NSString stringWithFormat:@"<html> \n"
                 "<head> \n"
                 "<style type=\"text/css\"> \n"
                 "body {font-size:.5rem;color:#1e242e;padding:0 .26rem;letter-spacing: .02rem;text-align: justify;}\n"
                 "</style> \n"
                 "</head> \n"
                 "<body>"
                 "<script type='text/javascript'>"
                 "window.onload = function(){\n"
                 "var $img = document.getElementsByTagName('img');\n"
                 "for(var p in  $img){\n"
                 " $img[p].style.width = '100%%';\n"
                 "$img[p].style.height ='auto'\n"
                 "}\n"
                 "}"
                 "</script>%@"
                 "</body>"
                 "</html>",content];
    }
    
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if(htmls == nil || htmls.length == 0){
            DDLog(@"load failed!")
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"数据加载出错" isExistNav:YES];
        }else{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.webView loadHTMLString:htmls baseURL:nil];
            });
            
        }
    });
    
}

-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{    
    //标题设置
    webView.scrollView.contentInset = UIEdgeInsetsMake(self.model.detailH, 0, 0, 0);
    YDVerticalStockNewDetailTitleView *topView = [[YDVerticalStockNewDetailTitleView alloc] init];
    topView.frame = CGRectMake(0, -self.model.detailH, LKScreenW, self.model.detailH);
    [webView.scrollView addSubview:topView];
    topView.model = self.model;
    
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"])
    {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1)
        {
            self.progressView.hidden = YES;
            [self.progressView setProgress:0 animated:NO];
        }
        else
        {
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    }
}

- (UIProgressView *)progressView
{
    if (!_progressView){
        UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, LKScreenW, 0)];
        progressView.tintColor = NumberColor(179, 84, 52);
        progressView.trackTintColor = NumberColor(179, 84, 52);
        [self.view addSubview:progressView];
        self.progressView = progressView;
    }
    return _progressView;
}

@end
